package com.yance.fim.cluster.zookeeper;

import com.alibaba.fastjson.JSON;
import com.yance.fim.config.ConfigParam;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Function: Zookeeper 工具
 *
 * @author crossoverJie
 *         Date: 2018/8/19 00:33
 * @since JDK 1.8
 */
@Component
public class ZKit {

    private static Logger logger = LoggerFactory.getLogger(ZKit.class);

    @Autowired
    private ZkClient zkClient;


    @Autowired
    private ConfigParam configParam ;

    /**
     * 创建父级节点
     */
    public void createRootNode(){
        try{
            boolean exists = zkClient.exists(configParam.getZkRoot());
            if (exists){
                return;
            }
            //创建 root
            zkClient.createPersistent(configParam.getZkRoot()) ;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 写入指定节点 临时目录
     *
     * @param path
     */
    public void createNode(String path) {
        zkClient.createEphemeral(path);
    }

    /**
     * get all server node from zookeeper
     * @return
     */
    public List<String> getAllNode(){
        List<String> children = zkClient.getChildren(configParam.getZkRoot());
        logger.info("Query all node =[{}] success.", JSON.toJSONString(children));
        return children;
    }
}
